<template>
  <div class="manage-posts">
    <div class="page-header">
      <h1>帖子管理</h1>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子标题或内容"
        prefix-icon="el-icon-search"
        clearable
        @clear="loadPosts"
      ></el-input>
      <el-button type="primary" @click="searchPosts">搜索</el-button>
    </div>

    <!-- 帖子列表 -->
    <el-table
      :data="posts"
      style="width: 100%"
      border
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
      @sort-change="handleSortChange"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
    >
      <el-table-column prop="title" label="标题" width="240">
        <template #default="scope">
          <div class="title-cell">{{ scope.row.title }}</div>
        </template>
      </el-table-column>
      <el-table-column label="配图" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            style="width: 60px; height: 60px"
            :src="getImageUrl(scope.row.image)"
            :preview-src-list="[getImageUrl(scope.row.image)]"
            :preview-teleported="true"
            fit="cover"
            lazy
          >
            <template #error>
              <div class="image-slot">加载失败</div>
            </template>
          </el-image>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="内容" width="380">
        <template #default="scope">
          <div class="content-cell">{{ scope.row.description }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者" width="120"></el-table-column>

      <el-table-column prop="publishScopeFormatted" label="发布范围" width="200">
        <template #default="scope">
          <div class="scope-cell">{{ scope.row.publishScopeFormatted }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="likesCount" label="点赞" width="100"></el-table-column>
      <el-table-column prop="commentsCount" label="评论" width="100"></el-table-column>
      <el-table-column prop="createdAt" label="发布时间" width="180">
        <template #default="scope">{{ scope.row.createTimeFormatted }}</template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
              size="small"
              type="primary"
              @click="viewPost(scope.row)"
            >详情</el-button>
          </el-tooltip>
          <el-tooltip content="编辑范围" placement="top">
            <el-button
              size="small"
              type="warning"
              @click="editScope(scope.row)"
            >编辑</el-button>
          </el-tooltip>
          <el-tooltip content="删除帖子" placement="top">
            <el-button
              size="small"
              type="danger"
              @click="confirmDelete(scope.row)"
            >删除</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 查看帖子详情对话框 -->
    <el-dialog
      title="帖子详情"
      v-model="showViewDialog"
      width="70%"
      top="5vh"
    >
      <div v-if="currentPost" class="post-detail">
        <h2>{{ currentPost.title }}</h2>
        <div class="post-meta">
          <span>作者: {{ currentPost.author }}</span>
          <!-- <span>社团: {{ currentPost.club }}</span> -->
          <span>发布时间: {{ currentPost.createTimeFormatted }}</span>
          <span>点赞: {{ currentPost.likesCount }}</span>
          <span>评论: {{ currentPost.commentsCount }}</span>
        </div>
        <div class="publish-scope-detail">
          <strong>发布范围:</strong> {{ currentPost.publishScopeFormatted }}
        </div>
        <div v-if="currentPost.image" class="post-image-detail">
          <h3>帖子图片</h3>
          <el-image
            style="width: 100%; height: 100%; border-radius: 4px;"
            :src="getImageUrl(currentPost.image)"
            :preview-src-list="[getImageUrl(currentPost.image)]"
            fit="contain"
            lazy
          >
            <template #error>
              <div class="image-slot">图片加载失败</div>
            </template>
          </el-image>
        </div>
        <div class="post-content">
          <h3>内容详情</h3>
          {{ currentPost.description }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showViewDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="showDeleteDialog"
      width="30%"
    >
      <p>确定要删除帖子 "{{ postToDelete?.title }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deletePost">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核拒绝对话框 -->
    <el-dialog
      title="拒绝帖子"
      v-model="showRejectDialog"
      width="40%"
    >
      <p>请输入拒绝原因:</p>
      <el-input
        v-model="rejectReason"
        type="textarea"
        rows="3"
        placeholder="请输入拒绝理由，将通知给发帖人"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialog = false">取消</el-button>
          <el-button type="warning" @click="confirmReject">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增：编辑发布范围对话框 -->
    <el-dialog
      title="编辑帖子发布范围"
      v-model="showEditScopeDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <div v-if="postToEditScope">
        <el-form label-width="120px">
          <el-form-item label="帖子标题:">
            <span>{{ postToEditScope.title }}</span>
          </el-form-item>

          <el-form-item label="发布到首页:">
            <el-switch v-model="editScopeForm.publishToHomepage"></el-switch>
          </el-form-item>

          <el-form-item label="发布到学校:">
            <div v-if="editScopeForm.publishToSchoolInfo">
              <el-tag
                :key="editScopeForm.publishToSchoolInfo._id"
                closable
                @close="removeSchoolScope"
                style="margin-right: 5px; margin-bottom: 5px;"
                >
                  {{ editScopeForm.publishToSchoolInfo.name }}
                </el-tag>
            </div>
            <span v-else style="color: #909399;">未发布到任何学校</span>
          </el-form-item>

          <el-form-item label="发布到社团:">
            <div v-if="editScopeForm.publishToClubsInfo && editScopeForm.publishToClubsInfo.length > 0">
               <el-tag
                  v-for="club in editScopeForm.publishToClubsInfo"
                  :key="club._id"
                  closable
                  @close="removeClubScope(club._id)"
                  style="margin-right: 5px; margin-bottom: 5px;"
                >
                  {{ club.clubname }}
                </el-tag>
            </div>
             <span v-else style="color: #909399;">未发布到任何社团</span>
          </el-form-item>

          <el-form-item>
              <p style="color: #E6A23C; font-size: 12px;">注意：管理员只能移除学校和社团范围，不能添加或更改。</p>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditScopeDialog = false">取消</el-button>
          <el-button type="primary" @click="saveScopeChanges" :loading="editLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';

// 状态变量
const posts = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const showViewDialog = ref(false);
const showDeleteDialog = ref(false);
const showRejectDialog = ref(false);
const currentPost = ref(null);
const postToDelete = ref(null);
const postToReject = ref(null);
const rejectReason = ref('');
const currentSort = ref({ prop: 'createdAt', order: 'descending' });
const showEditScopeDialog = ref(false);
const postToEditScope = ref(null);
const editScopeForm = ref({
  publishToHomepage: false,
  publishToSchoolInfo: null,
  publishToClubsInfo: []
});
const originalScope = ref({});
const editLoading = ref(false);

// 帖子状态转换函数
const getStatusType = (status) => {
  switch (status) {
    case 'published': return 'success';
    case 'pending': return 'warning';
    case 'rejected': return 'danger';
    default: return 'info';
  }
};

const getStatusText = (status) => {
  switch (status) {
    case 'published': return '已发布';
    case 'pending': return '待审核';
    case 'rejected': return '已拒绝';
    default: return '未知';
  }
};

// 获取 API 基础 URL 和 Token
const getApiUrl = (path) => `http://localhost:5000${path}`;
const getToken = () => localStorage.getItem('token');
const getImageUrl = (imageId) => imageId ? `${getApiUrl('/uploads/')}${imageId}` : '';

// 加载帖子数据
const loadPosts = async (resetPage = false) => {
  if (resetPage) {
    currentPage.value = 1;
  }
  loading.value = true;
  const token = getToken();
  if (!token) {
    ElMessage.error('用户未登录，无法获取帖子');
    loading.value = false;
    return;
  }

  try {
    const response = await axios.get(getApiUrl('/admin/posts'), {
      params: {
        page: currentPage.value,
        limit: pageSize.value,
        search: searchQuery.value,
        sort: currentSort.value.prop ? `${currentSort.value.prop},${currentSort.value.order}` : undefined
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (response.data && response.data.posts) {
      posts.value = response.data.posts.map(post => ({
        ...post,
        // 格式化时间
        createTimeFormatted: new Date(post.createdAt).toLocaleString()
      }));
      totalItems.value = response.data.pagination.total;
    } else {
      posts.value = [];
      totalItems.value = 0;
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error.response?.data?.message || error.message);
    ElMessage.error(`获取帖子列表失败: ${error.response?.data?.message || '请稍后再试'}`);
    // 处理权限错误
    if (error.response?.status === 401 || error.response?.status === 403) {
      console.log("权限不足或Token无效");
    }
  } finally {
    loading.value = false;
  }
};

// 搜索帖子
const searchPosts = () => {
  loadPosts(true);
};

// 清除搜索时重新加载
const clearSearch = () => {
  searchQuery.value = '';
  loadPosts(true);
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  console.log('Sort change:', prop, order);
  currentSort.value = { prop, order };
  loadPosts();
};

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadPosts();
};

// 查看帖子详情
const viewPost = (post) => {
  currentPost.value = post;
  showViewDialog.value = true;
};

// 通过帖子
const approvePost = async (post) => {
  try {
    // 这里应该是一个API调用
    // await axios.patch(`/api/posts/${post.id}/status`, { status: 'published' });
    
    // 模拟更新
    const index = posts.value.findIndex(p => p.id === post.id);
    if (index !== -1) {
      posts.value[index].status = 'published';
      // 同时更新原始数据
      const originalIndex = posts.value.findIndex(p => p.id === post.id);
      if (originalIndex !== -1) {
        posts.value[originalIndex].status = 'published';
      }
    }
    
    // 如果是从详情页审核，则关闭详情页
    if (showViewDialog.value) {
      currentPost.value.status = 'published';
      setTimeout(() => {
        showViewDialog.value = false;
      }, 1000);
    }
    
    ElMessage.success('帖子已通过审核');
  } catch (error) {
    console.error('审核帖子失败:', error);
    ElMessage.error('审核帖子失败');
  }
};

// 拒绝帖子（显示拒绝原因对话框）
const rejectPost = (post) => {
  postToReject.value = post;
  rejectReason.value = '';
  showRejectDialog.value = true;
};

// 确认拒绝
const confirmReject = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请输入拒绝原因');
    return;
  }
  
  try {
    // 这里应该是一个API调用
    // await axios.patch(`/api/posts/${postToReject.value.id}/status`, { 
    //   status: 'rejected',
    //   rejectReason: rejectReason.value
    // });
    
    // 模拟更新
    const index = posts.value.findIndex(p => p.id === postToReject.value.id);
    if (index !== -1) {
      posts.value[index].status = 'rejected';
      posts.value[index].rejectReason = rejectReason.value;
      
      // 同时更新原始数据
      const originalIndex = posts.value.findIndex(p => p.id === postToReject.value.id);
      if (originalIndex !== -1) {
        posts.value[originalIndex].status = 'rejected';
        posts.value[originalIndex].rejectReason = rejectReason.value;
      }
    }
    
    // 如果是从详情页拒绝，则更新详情页数据
    if (currentPost.value && currentPost.value.id === postToReject.value.id) {
      currentPost.value.status = 'rejected';
      currentPost.value.rejectReason = rejectReason.value;
      setTimeout(() => {
        showViewDialog.value = false;
      }, 1000);
    }
    
    showRejectDialog.value = false;
    ElMessage.success('已拒绝该帖子');
  } catch (error) {
    console.error('拒绝帖子失败:', error);
    ElMessage.error('拒绝帖子失败');
  }
};

// 确认删除
const confirmDelete = (post) => {
  postToDelete.value = post;
  showDeleteDialog.value = true;
};

// 删除帖子
const deletePost = async () => {
  if (!postToDelete.value) return;
  loading.value = true;
  const token = getToken();
  if (!token) {
    ElMessage.error('用户未登录，无法删除帖子');
    loading.value = false;
    showDeleteDialog.value = false;
    return;
  }

  try {
    await axios.delete(getApiUrl(`/posts/${postToDelete.value._id}`), {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    ElMessage.success('删除成功');
    showDeleteDialog.value = false;
    loadPosts();
    postToDelete.value = null;
  } catch (error) {
    console.error('删除帖子失败:', error.response?.data?.message || error.message);
    ElMessage.error(`删除帖子失败: ${error.response?.data?.message || '请稍后再试'}`);
    // 处理权限错误
    if (error.response?.status === 401 || error.response?.status === 403) {
      console.log("权限不足或Token无效");
    }
  } finally {
    loading.value = false;
  }
};

// 打开编辑范围对话框
const editScope = (post) => {
  postToEditScope.value = { ...post };
  editScopeForm.value = {
    publishToHomepage: post.publishToHomepage || false,
    publishToSchoolInfo: post.publishToSchool ? { _id: post.publishToSchool._id, name: post.publishToSchool.name } : null,
    publishToClubsInfo: post.publishToClubs ? [...post.publishToClubs] : []
  };
  originalScope.value = {
    schoolId: post.publishToSchool ? post.publishToSchool._id : null,
    clubIds: post.publishToClubs ? post.publishToClubs.map(c => c._id) : []
  };
  showEditScopeDialog.value = true;
};

// 移除学校范围
const removeSchoolScope = () => {
  editScopeForm.value.publishToSchoolInfo = null;
};

// 移除社团范围
const removeClubScope = (clubId) => {
  editScopeForm.value.publishToClubsInfo = editScopeForm.value.publishToClubsInfo.filter(club => club._id !== clubId);
};

// 保存范围修改
const saveScopeChanges = async () => {
  if (!postToEditScope.value) return;
  editLoading.value = true;
  const token = getToken();
  const payload = {
    publishToHomepage: editScopeForm.value.publishToHomepage,
    publishToSchool: editScopeForm.value.publishToSchoolInfo ? editScopeForm.value.publishToSchoolInfo._id : null,
    publishToClubs: editScopeForm.value.publishToClubsInfo.map(club => club._id)
  };
  console.log("Saving scope changes for post:", postToEditScope.value._id);
  console.log("Payload:", payload);
  try {
    const response = await axios.put(getApiUrl(`/admin/posts/${postToEditScope.value._id}/scope`), payload, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    ElMessage.success('发布范围更新成功');
    showEditScopeDialog.value = false;
    const index = posts.value.findIndex(p => p._id === postToEditScope.value._id);
    if (index !== -1 && response.data.post) {
      posts.value.splice(index, 1, response.data.post);
    } else {
      loadPosts();
    }
  } catch (error) {
    console.error('保存范围修改失败:', error.response?.data || error.message);
    ElMessage.error(`保存失败: ${error.response?.data?.message || '请稍后再试'}`);
  } finally {
    editLoading.value = false;
  }
};

// 组件加载时获取帖子列表
onMounted(() => {
  loadPosts();
});
</script>

<style scoped>
.manage-posts {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #ffffff;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.title-cell {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.content-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 400px;
}

.post-detail {
  padding: 10px;
  color: #d1d1d1;
}

.post-detail h2 {
  margin-top: 0;
  color: #66b1ff;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 10px 0 20px;
  color: #a0a0a0;
  font-size: 14px;
}

.post-content {
  margin: 20px 0;
  padding: 15px;
  background-color: #2c2c2c;
  border: 1px solid #444;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  
  h3{
    color: #66b1ff;
    width: 10vw;
    text-align: center;
    margin-bottom: 10px;
    justify-content: center;
    align-items: center;
  }
}

.post-images h3 {
  margin-top: 20px;
  font-size: 16px;
  color: #66b1ff;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.image-item {
  width: 150px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #555;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.el-dialog) {
  background-color: #28232e;
  color: #d1d1d1;
}
:deep(.el-dialog__title) {
  color: #ffffff;
}
:deep(.el-dialog__body) {
  color: #d1d1d1;
}
:deep(.el-dialog__footer) {
  background-color: #28232e;
}
:deep(.el-loading-mask) {
  background-color: rgba(40, 35, 46, 0.8);
}

:deep(.el-loading-spinner .path) {
  stroke: #66b1ff;
}

.scope-cell {
  white-space: normal;
  word-break: break-all;
  font-size: 12px;
  line-height: 1.4;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 12px;
}

.post-image-detail {
  margin-top: 15px;
  width: 100%;
  height: 300px;
  border: 1px solid #444;
  overflow: hidden;
  background-color: #2c2c2c;
  display: flex;
  justify-content: center;
  align-items: center;
  h3{
    width: 100%;
    text-align: center;
    margin-bottom: 10px;
    justify-content: center;
    align-items: center;
  }
}

.publish-scope-detail {
  margin: 15px 0;
  padding: 10px;
  background-color: #2c2c2c;
  border: 1px solid #444;
  border-radius: 4px;
  font-size: 14px;
}

.post-content h3 {
  margin-bottom: 10px;
  color: #66b1ff;
  font-size: 16px;
}

.el-table-column .el-button + .el-button {
  margin-left: 5px;
}

:deep(.el-dialog__body) {
  padding: 15px 25px;
}
</style> 